//
//  TestViewController.m
//  Founder_study
//
//  Created by hongbao.cui on 14-8-12.
//  Copyright (c) 2014年 com.founder. All rights reserved.
//

#import "TestViewController.h"
#import "FMSNetWorkModule.h"
#import "ZipArchive.h"
#import "SynExericisesPaperData.h"
#import "Sqlite.h"
#import "SwipeView.h"
#import "ApplicationUtils.h"
#import "PaperListView.h"
#import "XingAndLabel_UIView.h"
#import "ISMutileButton.h"
#import "ApplicationUtils.h"
#import "CaseQuestionView.h"
#import "IndexViewController.h"
#import "ResultViewController.h"
#import "FMNavgationItem.h"
#import "FMReachability.h"
@interface TestViewController ()<IndexBtnClickedDelegate>{
    NSInteger second;//计时器的秒
    NSInteger minutes;//计时器的分钟
    NSInteger hours;//计时器的小时
    NSTimer  *timer;
}
@end

@implementation TestViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)initNetData{
    NSString *urlString = [self.urlDict objectForKey:@"paperFileURL"];
    //    NSString *urlString = @"http://study.yuetong.cn:8080/drappub/rest/mobilestudy/paper/8056?authToken=feixiang0";
    //初始化Documents路径
    NSString *path = FMPAPERSAVE_PATH;//[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Paper"];
    FMSCHBLog(@"FMPAPERSAVE_PATH:%@",FMPAPERSAVE_PATH);
    if ([ApplicationUtils isFileExitsAtPath:path]) {
        FMSCHBLog(@"创建目录成功");
    }
    //初始化保存ZIP文件路径
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"paperID"]];
    NSString *status = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"status"]];
    NSString *paperStr = [NSString stringWithFormat:@"paper_%@.zip",paperId];
    NSString *filePath = [path stringByAppendingPathComponent:paperStr];
    [ApplicationUtils promptRotateWithViewTitle:@"加载中..." showView:self.view];
    [[FMSNetWorkModule sharedInstance] downloadFatAssFileFrom:urlString toFile:filePath completionCB:^(id result) {
        if (result == nil) {
            //初始化ZipArchive
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                                     0), ^{
                ZipArchive *zip = [[ZipArchive alloc] init];
                BOOL success = NO;
                if ([zip UnzipOpenFile:filePath]) {
                    success = [zip UnzipFileTo:path overWrite:YES];//解压文件
                    [zip UnzipCloseFile];//关闭
                    if (!success) {
                        //解压失败
                    }else {
                        //解压成功
                        FMSCHBLog(@"unzip success.............");
                        NSError *error = nil;
                        NSString *pathStr = [NSString stringWithFormat:@"%@/paper.XML",path];
                        NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:&error];
//    NSString *pathStr = [[NSBundle mainBundle] pathForResource:@"paper" ofType:@"xml"];
//     NSString *paperXmlString = [NSString stringWithContentsOfFile:pathStr encoding:NSUTF8StringEncoding error:&error];//test
                        if (!error) {
                            // 试题下载成功
                            FMSCHBLog(@"====== 试题下载成功 ======");
//                            NSArray *oldPaperData = [Sqlite selectTestQuestion:paperId];
//                            if (oldPaperData && oldPaperData.count > 0) {
//                                if ([Sqlite deleteTestQuestionIdAt:paperId]) {//清除试题成功，之后再保存
//                                    FMSCHBLog(@"试题清除成功");
//                                }else{
//                                    FMSCHBLog(@"试题清除失败!");
//                                }
//                            }
                            
                            SynExericisesPaperData *paperData = [[SynExericisesPaperData alloc] init];
                            NSMutableDictionary *paperDict = [paperData PaperData:paperXmlString];
                            FMSCHBLog(@"paperDict:%@",paperDict);
                            paper_title = [paperDict objectForKey:@"paper_title"];
                            paper_score = [paperDict objectForKey:@"paper_score"];
                            paper_time = [paperDict objectForKey:@"paper_time"];

                            NSMutableArray *array = [paperDict objectForKey:@"questions"];
                            NSMutableArray *questions = [NSMutableArray arrayWithCapacity:1];
                            if (!self.paperArray) {
                                self.paperArray = [NSMutableArray array];
                            }
                            NSInteger number = 0;
                            for (int i=0; i<[array count]; i++) {
                                NSMutableArray *questionArray = [[array objectAtIndex:i] objectForKey:@"question"];
                                NSString *qtype_name =  [[array objectAtIndex:i] objectForKey:@"type_name"];
                                NSNumber *myqtypeNumber = [[array objectAtIndex:i] objectForKey:@"myqtype"];
                                NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
                                NSString *myqtype = [numberFormatter stringFromNumber:myqtypeNumber];
                                [self.paperArray removeAllObjects];
                                [self.paperArray addObjectsFromArray:questionArray];
                                NSMutableString *answerStr_ = [[NSMutableString alloc] initWithCapacity:1];
                                for (int j=0; j<[self.paperArray count]; j++) {
                                    NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:j];
                                    [dataDict setObject:myqtype forKey:@"myqtype"];
                                    NSString *qtype = [dataDict objectForKey:@"qtype"];
                                    if ([qtype isEqualToString:@"1"]||[qtype isEqualToString:@"2"]) {
                                        [questions addObjectsFromArray:questionArray];
                                        NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:paperId,@"paper_id",[dataDict objectForKey:@"questionContent"],@"content",@"1",@"user_error_count",@"0",@"user_right_count",@"0",@"favourite_flag",@"0",@"user_test_sign",[dataDict objectForKey:@"orderid"],@"qst_no",@"",@"user_answer",status,@"collection_finish_flag",@"",@"userAnswerImage",nil];
                                        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:d];
                                        
                                        NSString *has_sub = [dataDict objectForKey:@"has_sub"];
                                        FMSCHBLog(@"cui---hong-------has_sub-----------%@",has_sub);
                                        if (has_sub) {
                                            [dataDict setObject:has_sub forKey:@"has_sub"];
                                        }
                                        [dataDict setObject:paper_title forKey:@"paper_title"];
                                        [dataDict setObject:paper_score forKey:@"paper_score"];
                                        [dataDict setObject:paper_time forKey:@"paper_time"];
                                        [dataDict setObject:qtype_name forKey:@"qtype_name"];
                                        [dataDict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"qst_no"];
                                        
#pragma mark - 上次答题记录数据库逻辑
                                        NSString *userAnswer = [Sqlite selectUserAnswerWithKey:@"user_answer" paperId:paperId questionId:dataDict[@"tq_id"]];
                                        if (userAnswer) {
                                            dict[@"user_answer"] = userAnswer;
                                            [Sqlite deleteTestQuestionIdAt:dataDict[@"tq_id"]];
                                        }
                                        [dataDict addEntriesFromDictionary:dict];
                                        BOOL success = [Sqlite insertTestQuestion:dataDict];
                                        if (success) {
                                            FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                        }else{
                                            FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                        }
                                        number++;
                                    }else if([qtype isEqualToString:@"3"]){
                                        //判断题
                                        [questions addObjectsFromArray:questionArray];
                                        NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:paperId,@"paper_id",[dataDict objectForKey:@"questionContent"],@"content",@"1",@"user_error_count",@"0",@"user_right_count",@"0",@"favourite_flag",@"0",@"user_test_sign",[dataDict objectForKey:@"orderid"],@"qst_no",@"",@"user_answer",status,@"collection_finish_flag",@"",@"userAnswerImage",nil];
                                        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:d];
                                        
                                        NSString *userAnswer = [Sqlite selectUserAnswerWithKey:@"user_answer" paperId:paperId questionId:dataDict[@"tq_id"]];
                                        if (userAnswer) {
                                            dict[@"user_answer"] = userAnswer;
                                            [Sqlite deleteTestQuestionIdAt:dataDict[@"tq_id"]];
                                        }
                                        
                                        NSArray  *array = [NSArray arrayWithObjects:@"正确",@"错误",nil];
                                        NSMutableDictionary *optionsDict = [NSMutableDictionary dictionaryWithCapacity:1];
//                                        NSArray *seArray = [NSArray arrayWithObjects:@"option_a",@"option_b", nil];
//                                        for (int i=0; i<[array count]; i++) {
//                                            NSString *str = [array objectAtIndex:i];
                                        [optionsDict setObject:array forKey:@"options"];
//                                        }
                                        NSString *has_sub = [dataDict objectForKey:@"has_sub"];
                                        FMSCHBLog(@"子题目：%@",has_sub);
                                        if (has_sub) {
                                            [dataDict setObject:has_sub forKey:@"has_sub"];
                                        }
                                        [dataDict addEntriesFromDictionary:optionsDict];
                                        [dataDict setObject:paper_title forKey:@"paper_title"];
                                        [dataDict setObject:paper_score forKey:@"paper_score"];
                                        [dataDict setObject:paper_time forKey:@"paper_time"];
                                        [dataDict setObject:qtype_name forKey:@"qtype_name"];
                                        [dataDict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"qst_no"];
                                        
                                        [dataDict addEntriesFromDictionary:dict];

                                        BOOL success = [Sqlite insertTestQuestion:dataDict];
                                        if (success) {
                                            FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                        }else{
                                            FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                        }
                                        number++;
                                    }
                                    else{//简答题,案例分析题
                                        NSString *has_sub = [dataDict objectForKey:@"has_sub"];
                                        FMSCHBLog(@"子题目：%@",has_sub);
                                        if (has_sub) {
                                            [dataDict setObject:has_sub forKey:@"has_sub"];
                                        }
                                        
                                        
                                        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:1];
                                        [answerStr_ appendFormat:@"<p>%@</p>",[dataDict objectForKey:@"answer"]];
                                        [dict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:answerStr_ forKey:@"answer"]];
                                        [dict addEntriesFromDictionary:[NSDictionary dictionaryWithObject:[dataDict objectForKey:@"questionContent"] forKey:@"content"]];
                                        [dict setObject:paperId forKey:@"paper_id"];
                                        [dict addEntriesFromDictionary:dataDict];
                                        [dict setObject:@"0" forKey:@"favourite_flag"];
                                        [dict setObject:paper_title forKey:@"paper_title"];
                                        [dict setObject:paper_score forKey:@"paper_score"];
                                        [dict setObject:paper_time forKey:@"paper_time"];
                                        [dict setObject:qtype_name forKey:@"qtype_name"];
                                        [dict setObject:[NSString stringWithFormat:@"%ld",(long)number] forKey:@"qst_no"];
                                        [dict setObject:@"" forKey:@"user_answer"];
                                        [dict setObject:status forKey:@"collection_finish_flag"];
                                        [dict setObject:@"" forKeyedSubscript:@"userAnswerImage"];
                                        
                                        // 输入的文本答案
                                        NSString *userAnswer = [Sqlite selectUserAnswerWithKey:@"user_answer" paperId:paperId questionId:dataDict[@"tq_id"]];
                                        if (userAnswer) {
                                            dict[@"user_answer"] = userAnswer;
                                            [Sqlite deleteTestQuestionIdAt:dataDict[@"tq_id"]];
                                        }
                                        
                                        // 图片答案
                                        NSString *userAnswerImage = [Sqlite selectUserAnswerWithKey:@"userAnswerImage" paperId:paperId questionId:dataDict[@"tq_id"]];
                                        if (userAnswer) {
                                            dict[@"userAnswerImage"] = userAnswerImage;
                                            [Sqlite deleteTestQuestionIdAt:dataDict[@"tq_id"]];
                                        }
                                        
                                        BOOL success = [Sqlite insertTestQuestion:dict];
                                        
                                        if (success) {
                                            FMSCHBLog(@"====cuihongbao===%d==>存储成功！",j);
                                        }else{
                                            FMSCHBLog(@"====cuihongbao=====>存储失败！");
                                        }
                                        [dict removeAllObjects];
                                        number++;
                                    }
                                }
                                
                            }
                            //删除paper.XML文件
                            BOOL success0 = [ApplicationUtils deleteExitsFile:pathStr];
                            if (success0) {
                                FMSCHBLog(@"删除paper.XML文件成功");
                            }
                            //删除zip文件
                              BOOL success1 = [ApplicationUtils deleteExitsFile:filePath];
                                if (success1) {
                                    FMSCHBLog(@"删除zip文件成功");
                                }
                            if (IS_STUDY) {
                                BOOL isReachable = [[FMReachability FMReachabilityWithHostname:@"www.baidu.com"] isReachable];
                                if (isReachable) {
                                    [self initAnswerData];
                                }
                            }else{//移动学习
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [ApplicationUtils promptRemove];
                                    if (IS_STUDY==0&&self.offLineOrNot==NO) {
                                        NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
                                        NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[self.urlDict objectForKey:@"paperID"],@"userName"];
                                        NSString *isFirst = [standard objectForKey:paperIDWithName];
                                        if ([isFirst isEqualToString:@"1"]) {
                                            NSString *button1Str = @"重新测试";
                                            NSString *button2Str = @"继续考试";
                                            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"上次没有做完该试题，是否继续?" delegate:self cancelButtonTitle:button1Str otherButtonTitles:button2Str, nil];
                                            alertView.tag = 2;
                                            [alertView show];
                                        }else{
                                            [self fileDownDone];
                                        }
                                    }else{
                                        [self fileDownDone];
                                    }
                                });
                            }
                        }
                    }
                }else{
                    // 回到主线程
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [ApplicationUtils promptRemove];
                        FMSCHBLog(@"open fail................");
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷解压失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [alert setTag:4];
                        [alert show];
                    });
                }
            });
        }else{
            if (_swipeView) {
                [_swipeView removeFromSuperview];
                _swipeView = nil;
            }
            [ApplicationUtils promptRemove];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert setTag:4];
            [alert show];
        }
    }];
}
//计时器
-(void)timerStart:(NSTimer *)_timer{
    second++;
    if (second>59) {
        minutes = minutes+1;
        second = 0;
    }
    if (minutes>59){
        hours = hours+1;
        minutes = 0;
    }
    UILabel *timeLabel = [_timer userInfo];
    NSString *timerString = [NSString stringWithFormat:@"%02li:%02li",hours*60+minutes,(long)second];
//    FMSCHBLog(@"timerString-----%@",timerString);
    [timeLabel setText:timerString];
    self.user_time = timerString;
}
//试卷试图的更新
-(void)initTestView:(NSString *)title{
//    NSMutableDictionary *dataDict = [self.paperArray objectAtIndex:currentPage];
//    NSString *paper_title_ = [dataDict objectForKey:@"paper_title"];
    NSString *paperTitleAndCount = [NSString stringWithFormat:@"%@",title];
    CGSize size = [paperTitleAndCount sizeWithFont:[UIFont systemFontOfSize:13.0] constrainedToSize:CGSizeMake(FMSCREENWIDTH-85, 35) lineBreakMode:NSLineBreakByWordWrapping];
    dispatch_async(dispatch_get_main_queue(), ^{
        [titleLabel setNumberOfLines:0];
        [titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
        [titleLabel setFont:[UIFont systemFontOfSize:13.0]];
        [titleLabel setText:paperTitleAndCount];
        [titleLabel setFrame:CGRectMake(10, (MAX(titleLabel.frame.size.height, 30)-size.height)/2, size.width, size.height)];
        [headerBg setFrame:CGRectMake(0, 0, FMSCREENWIDTH, MAX(titleLabel.frame.size.height, 30))];
        
        NSDictionary *dataDict = [self.paperArray objectAtIndex:0];//更新第一题收藏按钮
        //更新收藏按钮
        NSString *favourite_flag = [NSString stringWithFormat:@"%@",[dataDict objectForKey:@"favourite_flag"]];
        BOOL isCollection = NO;
        if ([favourite_flag isEqualToString:@"1"]) {
            isCollection = YES;
        }
        [collectionBtn setSelected:isCollection];
        if ([self.paperArray count]>0) {
            [_swipeView reloadData];
        }else{
            [_swipeView removeFromSuperview];
            _swipeView = nil;
        }
        [ApplicationUtils promptRemove];
        
        totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(FMSCREENWIDTH-100-20, 2, 100, headerBg.frame.size.height/2)];
        [totalLabel setTextColor:[UIColor whiteColor]];
        NSString *totaltext = [NSString stringWithFormat:@"%02i/%02lu",01,(unsigned long)[self.paperArray count]];;
        [totalLabel setText:totaltext];
        [totalLabel setFont:[UIFont systemFontOfSize:13.0]];
        [totalLabel setTextAlignment:NSTextAlignmentRight];
        [totalLabel setBackgroundColor:[UIColor clearColor]];
        [self.view addSubview:totalLabel];
        
        //计时器
        UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(FMSCREENWIDTH-100-20, 5+totalLabel.frame.size.height/2, 100, headerBg.frame.size.height/2)];
        [timeLabel setTextColor:[UIColor whiteColor]];
        [timeLabel setFont:[UIFont systemFontOfSize:13.0]];
        [timeLabel setTextAlignment:NSTextAlignmentRight];
        [timeLabel setBackgroundColor:[UIColor clearColor]];
        [self.view addSubview:timeLabel];
        if (!timer) {
            timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerStart:) userInfo:timeLabel repeats:YES];
        }
        self.rootTimer=timer;
        
        [self performSelector:@selector(locationUpdate) withObject:nil afterDelay:0.5];
    });
}
-(void)locationUpdate{//更新进度
    NSDictionary *dataDict = [self.paperArray objectAtIndex:0];
    NSInteger currentPage_flag = [[dataDict objectForKey:@"currentPage_flag"] integerValue];
    self.currentPage = currentPage_flag;
    _swipeView.currentPage = self.currentPage;
}
-(void)IndexBtnClicked:(UIButton *)sender{
    [_swipeView scrollToPage:sender.tag duration:0.2];
}
-(NSMutableArray *)getType:(NSString *)typeStr array:(NSMutableArray *)array{
    NSMutableArray *dataArray = [[NSMutableArray alloc] initWithCapacity:1];
    for (NSDictionary *dataDict in array) {
        NSString *qtype = [dataDict objectForKey:@"myqtype"];
        if ([qtype isEqualToString:typeStr]) {
            [dataArray addObject:dataDict];
        }
    }
    return dataArray;
}
#pragma mark-右侧答题卡按钮
-(void)rightBarBtnClicked:(id)sender{
    IndexViewController *index = [[IndexViewController alloc] initWithNibName:nil bundle:nil];
    NSMutableDictionary *dataQuestionDict = [NSMutableDictionary dictionaryWithCapacity:1];
    NSString *paper_id = [self.urlDict objectForKey:@"paperID"];
    NSMutableArray *array = [Sqlite selectTestQuestion:paper_id];
    NSMutableArray *dataArray1 = [self getType:@"0" array:array];//单选
    NSMutableArray *dataArray2 = [self getType:@"1" array:array];//多选
    NSMutableArray *dataArray3 = [self getType:@"2" array:array];//判断
    NSMutableArray *dataArray4 = [self getType:@"3" array:array];//填空
    NSMutableArray *dataArray5 = [self getType:@"4" array:array];//简答
    NSMutableArray *dataArray6 = [self getType:@"5" array:array];//简答
    NSMutableArray *dataArray7 = [self getType:@"6" array:array];//简答
    NSMutableArray *dataArray8 = [self getType:@"7" array:array];//简答
    NSMutableArray *dataArray9 = [self getType:@"8" array:array];//简答
    NSMutableArray *dataArray10 = [self getType:@"9" array:array];//简答

    NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:1];
    [dataArray1 count]>0?[list addObject:dataArray1]:NSLog(@"没有单选题");
    [dataArray2 count]>0?[list addObject:dataArray2]:NSLog(@"没有多选题");
    [dataArray3 count]>0?[list addObject:dataArray3]:NSLog(@"没有判断题");
    [dataArray4 count]>0?[list addObject:dataArray4]:NSLog(@"没有填空");
    [dataArray5 count]>0?[list addObject:dataArray5]:NSLog(@"没有主观题");
    [dataArray6 count]>0?[list addObject:dataArray6]:NSLog(@"没有支持题型");
    [dataArray7 count]>0?[list addObject:dataArray7]:NSLog(@"没有支持题型");
    [dataArray8 count]>0?[list addObject:dataArray8]:NSLog(@"没有支持题型");
    [dataArray9 count]>0?[list addObject:dataArray9]:NSLog(@"没有支持题型");
    [dataArray10 count]>0?[list addObject:dataArray10]:NSLog(@"没有支持题型");

    [dataQuestionDict setObject:list forKey:@"questions"];
    index.dataDict = dataQuestionDict;
    index.paper_idDict = self.urlDict;
    index.delegate = self;
    [self.navigationController pushViewController:index animated:YES];
}
-(void)initRightItemView{
    UIButton *itemBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [itemBtn setFrame:CGRectMake(0, 0, 20, 17)];
    [itemBtn setBackgroundImage:[ApplicationUtils getLocalImage:@"st_btn_class@2x"] forState:UIControlStateNormal];
    [itemBtn setBackgroundImage:[ApplicationUtils getLocalImage:@"st_btn_class0@2x"] forState:UIControlStateHighlighted];
    [itemBtn addTarget:self action:@selector(rightBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:itemBtn];
    self.navigationItem.rightBarButtonItem = item;
}

-(void)back{
    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
    NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[self.urlDict objectForKey:@"paperID"],@"userName"];
    NSString *isFirst = [standard objectForKey:paperIDWithName];
    if ([isFirst isEqualToString:@"1"]) {
        if (timer) {
            [timer setFireDate:[NSDate distantFuture]];
        }
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"是否保存做题记录?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存", nil];
        alertView.tag = 3;
        [alertView show];
    }else{
        [self dismissViewControllerAnimated:YES completion:^{
            [self releaseDealloc];
        }];
    }
    if (self.testVCBackBlock) {
        self.testVCBackBlock(self);
    }
}
-(void)initItem{
    FMNavgationItem* leftItem = [[FMNavgationItem alloc] init];
    [leftItem.backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItems = [leftItem getNavgationItemWithType:WRNavgationTypeLeft Ima:[ApplicationUtils getLocalImage:@"Navigation-Bar_Return_btn_@2x"] ImaHighlight:[ApplicationUtils getLocalImage:@"Navigation-Bar_Return_btn_@2x"] title:@""];
}
-(void)initSelfData{
    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
    NSString *paperIDWithName =[NSString stringWithFormat:@"%@_%@",[self.urlDict objectForKey:@"paperID"],@"userName"];
    NSString *isFirst = [standard objectForKey:paperIDWithName];
    [ApplicationUtils promptRotateWithViewTitle:@"加载中..." showView:self.view];
    if (!self.paperArray) {
        self.paperArray = [NSMutableArray array];
    }
    FMSCHBLog(@"study-%d-_offLineOrNot----%d",IS_STUDY,self.offLineOrNot);
    if (IS_STUDY==0&&self.offLineOrNot==NO) {//移动学习,每次都重新下载试题，离线做题时设置参数,YES时，离线使用
        [self initNetData];
        return;
    }
    if ([isFirst isEqualToString:@"1"]) {
        NSString *button1Str = @"重新测试";
        NSString *button2Str = @"继续考试";
        if (IS_STUDY) {
            button1Str = @"重新答题";
            button2Str = @"继续答题";
        }
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"上次没有做完该试题，是否继续?" delegate:self cancelButtonTitle:button1Str otherButtonTitles:button2Str, nil];
        alertView.tag = 2;
        [alertView show];
    }else{
        NSString *paperId = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"paperID"]];
        NSMutableArray *dataArray = [Sqlite selectTestQuestion:paperId];
        if ([dataArray count]>0) {
            if (IS_STUDY) {
                BOOL isReachable = [[FMReachability FMReachabilityWithHostname:@"www.baidu.com"] isReachable];
                if (isReachable) {
                    [self initAnswerData];
                }else{
                    [self.paperArray removeAllObjects];
                    [self.paperArray addObjectsFromArray:dataArray];
                    if ([self.paperArray count]>0) {
                        paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
                        paper_score = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_score"];
                        paper_time = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_time"];
                    }else{
                        [ApplicationUtils promptRemove];
                        return ;
                    }
                    [self initTestView:paper_title];
                }
            }else{//移动学习
                [self.paperArray removeAllObjects];
                [self.paperArray addObjectsFromArray:dataArray];
//                for (NSMutableDictionary *dict in self.paperArray) {
//                    [dict setObject:@"" forKey:@"user_answer"];
//                }
                if ([self.paperArray count]>0) {
                    paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
                    paper_score = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_score"];
                    paper_time = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_time"];
                }else{
                    [ApplicationUtils promptRemove];
                    return ;
                }
                [self initTestView:paper_title];
            }
        }else{
            [self initNetData];
        }
    }
}
#pragma mark-
#pragma mark-摇一摇
- (BOOL)canBecomeFirstResponder
{
    return YES;// default is NO
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"开始摇动手机");
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"stop");
    if (timer) {
        [timer setFireDate:[NSDate distantFuture]];
    }
    self.rootTimer = timer;
    UIAlertView *yaoyiyao = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"时间暂停" delegate:self cancelButtonTitle:@"开始答题" otherButtonTitles: nil];
    yaoyiyao.tag = 5;
    [yaoyiyao show];
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"取消");
}
#pragma mark-
#pragma mark-lifeCycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (IS_STUDY) {
        self.navigationItem.title = @"答作业";
    }else{
        self.navigationItem.title = @"试卷测试";
    }
    [self initItem];
    [self initSelfData];
    [self initRightItemView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fileDownDone) name:@"FILE_DOWNDONE" object:nil];
}
-(void)fileDownDone{
    NSString *paperId = [NSString stringWithFormat:@"%@",[self.urlDict objectForKey:@"paperID"]];
    NSMutableArray *array_afterSave = [Sqlite selectTestQuestion:paperId];
    if (!self.paperArray) {
        self.paperArray = [NSMutableArray arrayWithCapacity:1.0];
    }
    [self.paperArray removeAllObjects];
    [self.paperArray addObjectsFromArray:array_afterSave];
    if ([self.paperArray count]>0) {
        paper_title = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_title"];
        paper_score = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_score"];
        paper_time = [[self.paperArray objectAtIndex:0] objectForKey:@"paper_time"];
    }else{
        [ApplicationUtils promptRemove];
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"试卷加载失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert setTag:4];
//        [alert show];
        return ;
    }
    //计算得分
    for (NSDictionary *dict in self.paperArray) {
        NSString *user_Answer = [dict objectForKey:@"user_answer"];
        NSString *answer = [dict objectForKey:@"answer"];
        NSString *score = [dict objectForKey:@"score"];
        if ([user_Answer isEqualToString:answer]) {
            Sum = Sum+1*[score intValue];
        }
    }
    [self initTestView:paper_title];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (timer) {
        [timer setFireDate:[NSDate date]];
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [self releaseDealloc];
    if (timer) {
        [timer setFireDate:[NSDate distantFuture]];
    }
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[FMSNetWorkModule sharedInstance] cancleAllOperation];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    FMSCHBLog(@"===***********TestViewController==didReceiveMemoryWarning=====");
//    [self releaseDealloc];
}
-(void)releaseDealloc{
    if (timer) {
        [timer invalidate];
        timer=nil;
    }
    if(self.testVCBackBlock){
        self.testVCBackBlock = nil;
    }
    [[FMSNetWorkModule sharedInstance] cancleAllOperation];
    //清除UIWebView的缓存
    [ [NSURLCache  sharedURLCache ] removeAllCachedResponses];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)dealloc{
    [self releaseDealloc];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
@end
